const app = getApp();
const request = require('../../../utils/request.js');
Page({
  data: {
    userInfo: {},
    baseUrl: ''
  },

  onLoad() {
    this.loadUserInfo();
  },

  // 加载用户信息
  loadUserInfo() {
    const userInfo = wx.getStorageSync('userInfo') || {};
    this.setData({
      userInfo,
      baseUrl: app.globalData.baseUrl
    });
  },

  // 选择头像
  chooseAvatar() {
    let me = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        this.uploadAvatar(me,tempFilePath);
      }
    });
  },

  // 上传头像
  uploadAvatar(me,tempFilePath) {
    // 这里应该调用上传接口
    wx.uploadFile({
      url: `${app.globalData.baseUrl}/api/files/upload`,
      filePath: tempFilePath,
      name: 'file',
      header: {
        'Authorization': `Bearer ${app.getGlobalToken()}`
      },
      success(res) {
        const {
          data
        } = JSON.parse(res.data)
        const userInfo = me.data.userInfo
        userInfo.avatar = data
        me.setData({
          userInfo
        })
      },
      fail: () => {
        wx.showToast({
          title: '上传图片失败',
          icon: 'none'
        })
      }
    })
  },

  // 输入用户名
  onUsernameInput(e) {
    const userInfo = this.data.userInfo;
    userInfo.username = e.detail.value;
    this.setData({
      userInfo
    });
  },

  // 输入手机号
  onPhoneInput(e) {
    const userInfo = this.data.userInfo;
    userInfo.phone = e.detail.value;
    this.setData({
      userInfo
    });
  },

  // 输入邮箱
  onEmailInput(e) {
    const userInfo = this.data.userInfo;
    userInfo.email = e.detail.value;
    this.setData({
      userInfo
    });
  },

  // 选择地区
  onRegionChange(e) {
    this.setData({
      region: e.detail.value
    });
  },

  // 提交表单
  submitForm() {
    const {
      userInfo
    } = this.data;

    // 表单验证
    if (!userInfo.username) {
      wx.showToast({
        title: '请输入用户名',
        icon: 'none'
      });
      return;
    }

    if (!userInfo.phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
      return;
    }

    if (!userInfo.email) {
      wx.showToast({
        title: '请输入邮箱',
        icon: 'none'
      });
      return;
    }

    // 更新用户信息
    wx.setStorageSync('userInfo', userInfo);

    wx.showLoading({
      title: '保存中...'
    });

    // 这里应该调用更新用户信息的接口
    request.request({
      url: `${app.globalData.baseUrl}/api/user/wx/profile`,
      method: 'PUT',
      data: {
        avatar: this.data.userInfo.avatar,
        username: this.data.userInfo.username,
        phone: this.data.userInfo.phone,
        email: this.data.userInfo.email,
      },
      header: {
        'Authorization': `Bearer ${app.getGlobalToken()}`
      },
      success: (res) => {
        if(res.data.code === 200) {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          })
          setTimeout(() => {
            wx.navigateBack();
          }, 1500)
        }
      },
      fail: () => {
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        })
        console.error('保存失败:', err)
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  }
});